<?php

class Avatarmodel extends Model 
{
	
	var $avatar_path;
	
	function Avatarmodel() 
	{
		parent::Model();
		
	}
	
	function upload_avatar($userId)
	{

		$this->avatar_path = realpath(APPPATH . 'userdata/profile_' . $userId . '/avatars/');
		
		$config = array(
			'allowed_types' => 'jpg|jpeg|png',
			'upload_path' => $this->avatar_path,
			'max_size' => 1024
		);
		
		$this->load->library('upload', $config);
		$this->upload->do_upload();
		$image_data = $this->upload->data();
		
		$config = array(
			'source_image' => $image_data['full_path'],
			'new_image' => $this->avatar_path . '/thumbs/',
			'maintain_ration' => true,
			'width' => 80,
			'height' => 80
		);
		
		$this->load->library('image_lib', $config);
		$this->image_lib->resize();

		if($image_data['file_size'] > 0)
		{
		$this->db->where('user_id', $userId);
		$this->db->update('users', array('avatar' => $image_data['file_name']));
		}
		else
		{
			$this->session->set_flashdata('error',  'คุณยังไม่ได้เลือกภาพประจำตัวรึเปล่า?');
			redirect('profile/uploadAvatar');
		}
		
		if($image_data['file_size'] > 1024)
		{
			$this->session->set_flashdata('error', 'ไฟล์ภาพมีขนาดใหญ่เกินไป');
			redirect('profile/uploadAvatar');
		}
	}
} 